/*
 * @Author: linZeJian
 * @Date: 2022-10-18 15:47:07
 * @LastEditors: linZeJian
 * @LastEditTime: 2022-11-10 11:16:54
 * @Description: 
 */

import {
  deepClone
} from "./deepClone.js";
import {
  validatenull
} from "./methods";
import request from "@/util/request/index.js";
import {
  bmoUrl,
} from "@/util/config/config.js"

/**
 * @description: 处理配置，c子表单与crud未做处理，完善后再同步到子表单与crud
 * @param {*} option,detail
 * @return {*}
 */
export default function handleAvueOption(option, detail, that) {
  let resultData = option || null;
  // console.log('option111 :>> ', option);
  // 处理普通表单的column
  if (resultData.column && resultData.column.length > 0) {
    resultData.column.forEach((item) => {
      item = handleOptionItem(item, detail, resultData, that);
      // 下拉选择项确定数据
      // item.change = (() => {console.log('666666', 666666)})
    });
  }
  // 处理分组group
  if (resultData.group && resultData.group.length > 0) {
    resultData.group.forEach((item) => {
      item.column.forEach((item2) => {
        item2 = handleOptionItem(item2, detail, resultData, that);
      });
    });
  }
  return resultData;
}

/**
 * @description: 表单项多项处理时抽取
 * @param {*} item
 * @return {*}
 */
function handleOptionItem(item, detail, resultData, that) {
  // 部分column项不存在display可见属性,手动添加
  item.display = 'display' in item ? item.display : true;
  // 注意只读模式跟禁用模式暂未使用,readonly: true,disabled: true,相关适配待定,计算属性统一配置
  // 自定义全局详情模式与option全局详情模式detail,适配处理
  if (detail || resultData.detail) {
    // 配置到每一项子项
    item.detail = true;
    // 详情模式去掉必填标识
    item.required = false;
  }
  // dynamic子表单,customCrud部分相关配置在子表单组件内适配
  if (item.type == "dynamic") {
    let children = deepClone(item.children);
    children.column.forEach((dynamicItem) => {
      // 循环子表单项
      dynamicItem = handleOptionItem(dynamicItem, detail, resultData, that);
    });
    that.$set(item, "children", children);
  }
  // customCrud子表单部分相关配置在子表单组件内适配
  if (item.type == "customCrud") {
    // crud子表单项放在params.formOption里,转存到children
    let children = deepClone(item.params.formOption);
    // console.log('children :>> ', children);
    children.column.forEach((dynamicItem) => {
      // 循环子表单项
      dynamicItem = handleOptionItem(dynamicItem, detail, resultData, that);
    });
    that.$set(item, "children", children);
  }
  // customGroup对象子表单部分相关配置在子表单组件内适配
  if (item.type == "customGroup") {
    let children = deepClone(item.children);
    children.column.forEach((dynamicItem) => {
      // 循环子表单项
      dynamicItem = handleOptionItem(dynamicItem, detail, resultData, that);
    });
    that.$set(item, "children", children);
  }

  // 后台同步适配（2022.10.11）
  // 下拉选择项定制数据
  if (item.type == "select") {
    // item.change = () => {
    //   console.log("666666", 666666);
    // };
    // 处理下拉选择框的定制属性
    item = handleCustomizedItem(item, resultData, that);
  }
  return item;
};
/**
 * @description: 处理下拉选择框的定制属性
 * @param {*} item
 * @return {*}
 */
async function handleCustomizedItem(item, resultData, that) {
  // console.log("item", item);
  // 处理数据模型
  if (!validatenull(item.dicTableId)) {
    try {
      let response = await getTableData(
        item.dicTableId,
        item.dicTableQuery
      );
      console.log('response :>> ', response);
      // item.dicData = response.data;
      that.$set(item, "dicData", response.data);
      // 将dicData的key，value的字典更换成props的配置字典
    } catch (err) {
      console.error(
        `初始化数据表失败:${item.dicTableId} ${item.dicTableQuery}`,
        err
      );
    }
  }
  // 处理自定义事件eventList
  // 添加点击确认事件
  // console.log("item22222", item);
  if (item.eventList && item.eventList.length > 0) {
    // console.log('111 :>> ', 111);
    item.change = async (value) => {
      // console.log("666666", that);
      let component = findAvue(that);
      // console.log("component", component);
      if (component) {
        for (const sender of item.eventList) {
          await generateSenderEvent(
            item,
            sender,
            value,
            resultData,
            component,
            that
          );
        }
      }
    };
  } else {
    item.change = (value) => {
      console.log("00000", value);
    };
  }
  // console.log("item2222", item);
};
// 数据请求抽离到aform组件外的父组件事件来调用请求
/**
 * @description: 数据模型配置的相关请求
 * @param {*} tableId
 * @param {*} query
 * @return {*}
 */
async function getTableData(tableId, query) {
  console.log('11111 :>> ', 11111);
  let searchList = [];
  if (query && query.searchKey) searchList.push(query);
  let obj = {
    searchList: searchList,
  }
  // let res = await request.getFormTableDbData(tableId, obj);
  let res = await request.POST({
    url: `/bmo/api/v1/form/table/db/data/${tableId}`,
    data: obj,
    baseURL: bmoUrl,
  })
  console.log('res1111 :>> ', res);
  return res;
}
/**
 * @description: 从this全局对象中获取Avue组件配置
 * @param {*} vueComponent
 * @return {*}
 */
function findAvue(vueComponent) {
  console.log("vueComponent", vueComponent);
  console.log(
    'vueComponent.$vnode.tag.endsWith("Aform")',
    vueComponent.$vnode.tag.endsWith("Aform")
  );
  if (vueComponent.$vnode.tag.endsWith("Aform")) {
    return vueComponent;
  }
  if (vueComponent.$parent) {
    return findAvue(vueComponent.$parent);
  }

  return undefined;
};
/**
 * @description: 处理事件绑定关系
 * @param {*} c
 * @param {*} sender
 * @param {*} value
 * @param {*} option
 * @param {*} component
 * @param {*} vue
 * @return {*}
 */
async function generateSenderEvent(c, sender, value, option, component, vue) {
  try {
    let column = getColumnByProp(sender.receiver.prop, option);
    if (column) {
      let data = null;

      // 处理数据源
      // 数据模型，请求配置数据
      if (sender.source.type === "tableModel") {
        let res = await getTableData(
          sender.source.tableModel.tableId, {
            ...sender.source.tableModel.query,
            searchVal: value,
          }
        );
        data = res;
      } else if (sender.source.type === "selfDic") {
        // 表单本身配置数据字典
        let fieldData = c.dicData.find((d) => d[c.props.value] === value);
        if (fieldData) {
          data = fieldData[sender.source.selfDic.field.at(-1)];
        }
      } else if (sender.source.type === "selfValue") {
        // 表单本身的值
        data = value;
      }
      console.log('data000 :>> ', data);

      // 返回结构: 配置处理
      if (sender.source.tableModel.formatter) {
        data = OptionFormatterFunc(data, sender.source.tableModel.formatter);
        // console.log(data, 478);
      }

      // console.log('data1111 :>> ', data);
      // console.log('sender1111 :>> ', sender);
      // 接收方式
      // 事件绑定直接复制到this的Avue配置上
      if (sender.receiver.type === "dic") {
        vue.$set(component.form, column.prop, undefined);
        vue.$set(column, "dicData", data);
        vue.$set(column, "props", sender.receiver.props);
      } else if (sender.receiver.type === "value") {
        vue.$set(component.form, column.prop, data);
      }

      // console.log('component111', component)
    }
  } catch (err) {
    console.error("发送事件异常", err);
  }
};
/**
 * @description: 返回满足条件的Column
 * @param {*} receiverProp
 * @param {*} option
 * @return {*}
 */
function getColumnByProp(receiverProp, option) {
  // return _.find(option.column, {
  //   prop: receiverProp
  // });
  return option.column.find(({
    prop
  }) => prop === receiverProp)
};

/**
 * @description: eval()把对应的字符串解析成js代码并运行，处理返回数据配置
 * 结构配置：
 * (res) {
  return res.data[0].p2_modules;
}
 * @param {*} val
 * @param {*} code
 * @return {*}
 */
function OptionFormatterFunc(val, code) {
  let r = "";
  let func =
    "function CustomOptionFormatterFunc" +
    code +
    "\n r = CustomOptionFormatterFunc(val)";
  console.log('func', func)
  eval(func);
  return r;
}